package weather.com.weather

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import weather.com.weather.adapter.FutureWeatherAdapter
import weather.com.weather.bean.WeatherBean
import java.io.IOException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity(), View.OnClickListener {

    //    var url = "http://v.juhe.cn/weather/index?format=2&cityname=广州&key=7a819e323bd6fc0f75d1f9f6e6cecc47"

    var city: TextView? = null
    var temp: TextView? = null
    var wind: TextView? = null
    var windPower: TextView? = null
    var humidity: TextView? = null
    var uvRays: TextView? = null
    var meteorological: TextView? = null

    val h = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg!!.what) {
                0 -> {
                    /**
                     * 解析Json数据
                     */
                    Log.d("Handler检查数据", msg.data.getString("data"))
                    var res = Gson().fromJson(msg.data.getString("data"), WeatherBean::class.java)
                    Log.d("请求回来的数据", res.toString())
                    Toast.makeText(this@MainActivity, "请求完成", Toast.LENGTH_SHORT).show()
                    analyticDisplay(res)
                }
            }
        }
    }

    fun analyticDisplay(data: WeatherBean) {
        if (data.resultcode == "200") {
            city_main.text = data.result.today.city
            temp!!.text = data.result.sk.temp + "℃"
            wind!!.text = data.result.sk.windDirection
            windPower!!.text = data.result.sk.windStrength
            humidity!!.text = data.result.sk.humidity //时间
            meteorological!!.text = data.result.today.weather
            uvRays!!.text = data.result.today.uvIndex + "强度"
            //设置未来几天天气数据
            future_weather.adapter = FutureWeatherAdapter(this@MainActivity, data.result.future)
            setListViewHeightBasedOnChildren(future_weather)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var cityControl = findViewById<ImageButton>(R.id.city_control)
        city = findViewById<TextView>(R.id.city_main)//城市
        temp = findViewById<TextView>(R.id.temperature_main)//今天温度
        wind = findViewById<TextView>(R.id.wind)//今天风向
        windPower = findViewById<TextView>(R.id.wind_power)//今天风力
        humidity = findViewById<TextView>(R.id.humidity)//今天湿度
        uvRays = findViewById<TextView>(R.id.uv_rays)//今天紫外线强度
        meteorological = findViewById<TextView>(R.id.meteorological)//今天的气象


        cityControl.setOnClickListener(this)

        var userSettings = getSharedPreferences("citymessage", 0)
        var edit = userSettings.edit()
        if (userSettings.getString("cityname", "默认值") == "默认值") {
            edit.putString("cityname", "广州")
            edit.commit()
        }
        http(userSettings.getString("cityname", "点击添加城市"))
    }

    fun setListViewHeightBasedOnChildren(listView: ListView) {
        var listAdapter = listView.adapter
        if (listAdapter == null) return
        var totalHeight = 0
        var len = listAdapter.count
        for (index in 0..len - 1) {
            var listItem = listAdapter.getView(index, null, listView)
            listItem.measure(0, 0)
            totalHeight += listItem.measuredHeight
        }
        var params = listView.layoutParams
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        params.height = totalHeight + (listView.dividerHeight * (listAdapter.count - 1))
        // params.height最后得到整个ListView完整显示需要的高度
        listView.layoutParams = params
    }

    override fun onClick(v: View?) {
        if (v != null) {//判断View是否为null
            when (v.id) {
                R.id.city_control -> {
                    startActivityForResult(Intent(this, CityControl::class.java), 0)
                }
            }
        }
    }

    fun http(name: String) {
        var url = "http://v.juhe.cn/weather/index?format=2&dtype=&cityname=${name}&key=7a819e323bd6fc0f75d1f9f6e6cecc47"
        var ddd: String = ""
        Thread(object : Runnable {
            override fun run() {
                var client = OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).build() //创建对象

                var request = Request.Builder().url(url).build()//建立连接
                var call = client.newCall(request)
                call.enqueue(object : Callback{
                    override fun onFailure(call: Call?, e: IOException?) {
                       // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                        if(e is SocketTimeoutException){//判断超时异常
                            Toast.makeText(this@MainActivity,"请求超时",Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onResponse(call: Call?, response: Response?) {
                       // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                        var data: String = response!!.body()!!.string()
                        Log.d("测试返回的数据", data)
                        ddd = data
                        var bundle = Bundle()//创建Bundle对象用来存储数据
                        bundle.putString("data", data)//给bundle设置数据
                        var me = Message.obtain()
                        me.data = bundle//
                        me.what = 0
                        h.sendMessage(me)
                    }
                })
//                var response = client.newCall(request).execute()

            }
        }).start()
    }

        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 0 && data != null){
            var name = data!!.getStringExtra("cityname")
            http(name)
            var userSettings = getSharedPreferences("citymessage", 0)
            var edit = userSettings.edit()
            edit.putString("cityname", name)
            edit.commit()
        }
        else
            Toast.makeText(this, "没有选择城市", Toast.LENGTH_SHORT).show()
    }
}
